function getGKeepId(infos) {
    for (var i = 0; i < infos.length; ++i) {
        if (infos[i].name.toLowerCase() === 'Google Keep'.toLowerCase()) {
            return infos[i];
        }
    }
    return null;
}

function getKeepUrl() {
    return 'https://keep.google.com/';
}

function launchApp(id) {
    chrome.management.launchApp(id);
}

function createTabGKeep() {
    chrome.tabs.query({
        url : '*://keep.google.com/*'
    }, function(tabs) {
        if (tabs.length > 0) {
            chrome.tabs.update(tabs[0].id, {
                'selected' : true
            });
            return;
        }

        chrome.tabs.create({
            'url' : getKeepUrl()
        });
    });
}

function listenForGKeepCreation() {
    chrome.storage.sync.get('site', function(data) {
        if (data.site) {
            createTabGKeep();
        } else {
            chrome.management.getAll(function(infos) {
                var info = getGKeepId(infos);

                if (!info) {
                    createTabGKeep();
                } else {
                    launchApp(info.id);
                }
            });
        }
    });
}

chrome.browserAction.onClicked.addListener(listenForGKeepCreation);